const Service = require('egg').Service;
const SocketService = require('./socketService');
/**
 * 数据订阅缓存，当前采用内存缓存，正式应缓存到redis中
 */
const DATA_SUBSCRIBES = {
  datas: {},
  getDatas: function(name) {
    const datas = this.datas[name] || (this.datas[name] = {})
    return datas
  },
  getDataSubscribes: function(name, id) {
    const datas = this.getDatas(name)
    return datas[id] || (datas[id] = {})
  },
  subscribe: function ({ name, id, connectionId }) {
    if (!name || !id || !connectionId) {
      throw new Error('数据订阅的参数错误！');
    }
    const ids = id instanceof Array ? id : [id];
    ids.forEach(dataId => {
      const connectionIds = this.getDataSubscribes(name, dataId)
      connectionIds[connectionId] = true
    })
  },
  unsubscribe: function ({ name, id, connectionId }) {
    // to do...
  }
};

/**
 * 数据订阅服务
 */
class DataSubscribeService extends Service {
  constructor(app) {
    super(app);
  }

  /**
   * 订阅数据消息
   * @param {*} data 
   */
  subscribe(data) {
    DATA_SUBSCRIBES.subscribe(data);
  }

  /**
   * 发布数据
   * @param {*} param0 
   */
  publish({ name, id, data }) {
    const connectionIds = DATA_SUBSCRIBES.getDataSubscribes(name, id);
    Object.keys(connectionIds).forEach(connectionId => {
      SocketService.pushMessages({
        method: 'updateData',
        connectionId,
        messages: {
          id,
          name,
          data
        }
      });
    });
  }
}

module.exports = DataSubscribeService;